import React, { useState, useEffect } from 'react';
import './FriendInfo.less'
import systemStore from '../../store/SystemStore';
import mainStore from "../../store/MainStore";
import { Avatar, Icon, message } from 'antd';
import { Input,Button } from 'antd';
import ChatStore from '../../store/ChatStore';

import { formatAvatarFromUserid } from '../../utils/avatarUtils';
import imsdk from '../../net/IMSDK';
import SvgIcon from '../../component/svgIcon/SvgIcon';
import { AvatorWithPhoto } from '../../component/avatorWithPhoto/AvatorWithPhoto';
import { ChatGrOrFrType } from '../../interface/IChat';
import { avatorData } from '../../config/chatUserPhotoData';
export default function FriendInfo(){
  const [friendData, setFriendData] = useState<any>({});
  const [isEditing, setIsEditing] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState('');
  const [editDescClass, setEditDescClass] = useState('editDesc hidden');
  const [saveremark, setSaveremark]=useState(false);
  const [writeremark, setWriteremark]=useState('');
  const { TextArea } = Input;
  const defaultImage = require('../../assets/image/im_notice_square.png');
  const [noRemind,setNoRemind] = useState(false);


  useEffect(() => {
    
    setAvatarUrl('');
    setFriendData({})
    setIsEditing(false);
    setEditDescClass('editDesc hidden');
    
    // 发起网络请求的异步函数
    const fetchData = async () => {
      // console.log("执行这里IMSDK",imsdk)
      console.log("执行这里mainStore.friend",mainStore.friend)
      const member:any = mainStore.friend;
      //const userId = member.userId || member.toUserId || member.userId
      const friendid =  member.toUserId || member.userId
      const response = await imsdk.getUserInfo(friendid);
      // console.log("imsdkdata",response)
      // console.log("chatStore.chats",ChatStore.chats)
      const chatItem = ChatStore.chats.find(item => item.id == friendid);
      console.log("chatItem",chatItem)
      // console.log("当前这个人的",chatItem.isNotice)
      if (chatItem) {
        setNoRemind(Boolean(chatItem.isNotice))
      }
      //userType 1=普通用户；  2=公众号 ；3=机器账号，由系统自动生成；4=客服账号, 5企业帐号
      // 目前1 3 4的数据结构一致，这里对2公众号做处理
      if(!response.data){
        
        //message.error('获取好友信息失败');
        console.error('获取好友信息失败');
        return;
      }
      if (response.data.userType == 2 ) {
        let address = ''
        try{
          address = response.data.ipAnalysisVO? response.data.ipAnalysisVO.address:''
        }catch(err){}
        setAvatarUrl(defaultImage);
        setFriendData({
          userId:response.data.userId,
          userType: response.data.userType,   
          nickname:response.data.nickname,
          loginLog:response.data.loginLog,
          account:'客服号暂时没有账号ID',
          telephone:response.data.telephone,
          remark:response.data.remark,
          address:address            
        })
        setWriteremark(response.data.remark)
      }else{
        // 使用 formatAvatarFromUserid 生成头像 URL
        // 格式 'https://47.97.61.50:8089/avatar/o/11/10000011.jpg'
        if( response.data.userType == 5 || response.data.userType == 1){
          const url = await avatorData.getAvatorData(response.data.userId);
          setAvatarUrl(url);
        }else{
          try {
            setAvatarUrl(formatAvatarFromUserid(friendid.toString()));
            // console.log('头像地址格式化成功:', avatarUrl);
          } catch (err) {
            // console.error('头像地址格式化失败:', err);
            // avatarUrl = '/static/media/e-7.1967ac56.png'; // 默认头像 URL
          }
        }
        
        let address = ''
        try{
          address = response.data.ipAnalysisVO? response.data.ipAnalysisVO.address:''
        }catch(err) {}
        setFriendData({
          ...response.data,
          address
        })
        // console.log('怎么不刷新')
      }
      setEditDescClass('editDesc');
      // setNoRemind();
      // console.log('look',noReadMsgNumber(friendid))
    };
    fetchData();
  }, [mainStore.friend]); // 副作用订阅

  // console.log("观察avatarUrl:",avatarUrl)


  const handleEditDesc = () => {
    setIsEditing(true);
  }
  const handleSubmitDesc =async () => {
    setSaveremark(true);
    const friend:any = mainStore.friend
    const response =await imsdk.updateUserMarkInfo(friend.toUserId || friend.userId, {
      userId:friend.toUserId || friend.userId,
      remark:writeremark
    });
    console.log("looklook",response)
    if (response.resultCode == 1) {//修改成功
      setFriendData({
        ...friendData,
        remark: writeremark
      });
      setIsEditing(false);
    }else{
      message.error('修改备注失败');
    }
    setSaveremark(false);
  }

  // 希望自动保存就在这里执行,这里监听异步的setFriendData
  // 或者handleChange的event.target.value去请求，都行。
  // useEffect(() => {
  //   console.log("changeremark.remark",friendData.remark)
  // }, [friendData.remark]);

  const handleChange = (event) => {
    setWriteremark(event.target.value)
    // setFriendData({
    //   ...friendData,
    //   remark: event.target.value
    // });
  };

  const sendMsgToFriend = () => {
		ChatStore.changeCurrentChat(mainStore.friend);
  }


  

    const item = friendData;
    let userId = item.account;
    if( !/^\d+/.exec(userId)){
      // 兼容一下
      userId = item.userId
    }

    return <div className="friend-info">
        <div className='friend-info-box'>
          <div className='friend-info-box-line1'>
            {/* <Avatar style={{backgroundColor: '#ffffff'}}  shape="square" size={60} src={avatarUrl}/> */}
            <AvatorWithPhoto 
              // avator={avatarUrl+''}
              forceUpdate={true}
              type={ChatGrOrFrType.friend} 
              userType={item.userType || item.toUserType}
              onlineStyle='dot'
              onlinestate={item.onlinestate}
              id={userId} classN="userphoto"
              size={60}
              />
            <div className='friend-info-box-line1-name'>{friendData.nickname}</div>
            {/* <div className='friend-info-box-line1-name'>{friendData['nickname']}</div> */}
          </div>
          <div className='friend-info-box-line2'>
            <div  className='info-title'>
              <div className='info-title-line'></div>
              <div>访问信息</div>
            </div>
            <div className='info-list'>
              <div className='info-list-item'><div className='info-list-title'>地区:</div> <div className='info-list-txt'>{friendData.address}</div></div>
              <div className='info-list-item'><div className='info-list-title'>登录设备:</div> <div className='info-list-txt'>{friendData.loginLog?friendData.loginLog.appBrand:''}</div></div>
            </div>
          </div>
          
          <div className='friend-info-box-line2'>
            
          <div  className='info-title'>
              <div className='info-title-line'></div>
              <div>注册信息</div>
            </div>
            <div className='info-list'>
              <div className='info-list-item'><div className='info-list-title'>账号ID:</div><div className='info-list-txt'>{userId}</div></div>
              <div className='info-list-item'><div className='info-list-title'>昵称:</div> <div className='info-list-txt'>{friendData.nickname}</div></div>
              <div className='info-list-item'><div className='info-list-title'>电话:</div> <div className='info-list-txt'>{friendData.telephone==''?'':friendData.telephone}</div></div>
            </div>
          </div>
          <div className='friend-info-box-line4'>
            <div className='friend-info-box-line4-title'>备注信息:</div>
            {isEditing ? (
              // maxLength={2000} 限制最大长度问后端
              <div style={{flexGrow:1}}>
                <TextArea rows={4} style={{maxHeight: '168px',minHeight: '84px'}} placeholder="请填写备注信息"  maxLength={2000} defaultValue={friendData.remark} onChange={handleChange}/>
                <Button type="default" style={{marginTop: '4px'}} onClick={()=>setIsEditing(false)}>取消</Button>
                <Button type="primary" style={{marginTop: '4px',marginLeft: '10px'}} loading={saveremark}  onClick={handleSubmitDesc}>完成</Button>
              </div>
            ) : (
              <div style={{display: 'flex', alignItems: 'center',gap: '3px'}} className={`${editDescClass}`} onClick={handleEditDesc}>{friendData.remark?friendData.remark:'请填写备注信息'} <SvgIcon name="edit" size='12'></SvgIcon></div>
            )}
          </div>
          <div className='friend-info-box-line5'>
            <Button type="primary" onClick={sendMsgToFriend} className='friend-info-box-line5-btn'><SvgIcon name="sendmsg" size='16'></SvgIcon>发起消息</Button>
            <Button disabled type="primary" className='friend-info-box-line5-btn'><SvgIcon name="tel" size='16'></SvgIcon>语音通话</Button>
            <Button onClick={()=>{
              console.log('看一下friendData.userId',friendData.userId)
              ChatStore.setNotice(friendData.userId,!noRemind)
              setNoRemind(!noRemind)
            }} type="primary" ghost className='friend-info-box-line5-btn'>{
               noRemind ? <SvgIcon name="mute" size='16'></SvgIcon> : <SvgIcon name="mute_no" size='16'></SvgIcon>
              }消息免打扰</Button>
            {/* <Button type="primary" ghost className='friend-info-box-line5-btn'><img src={iconDel} />删除联系人</Button> */}
          </div>
        </div>
        {/* FriendInfo:{JSON.stringify(friendData)} */}
        {/* <button onClick={()=>// console.log("aaa")}>click</button> */}
        {/* <HelloComponent></HelloComponent> */}
    </div>
}

